<?php
namespace Admin\Controller;

use Common\Lib\Tree;
use Think\Page;

class GoodsController extends AdminController {

    private $_category_cache = 'goods_categroy_cache';

    public function index() {
        $keyword = I('keyword', '', 'addslashes,trim');
        $cpage = (int)$_GET['p'] > 0 ? (int)$_GET['p'] : 1;
        $where = [];
        if (!empty($keyword)) {
            $where['A.goods_name'] = ['like', "%{$keyword}%"];
        }

        $result = M('Goods')->alias('A')->field('A.*,B.nickname')
            ->join(C('DB_PREFIX') . 'user as B ON A.supplier_id = B.id', 'left')
            ->where($where)->order('id DESC')->page($cpage, $this->page_size)->select();

        $count = M('Goods')->alias('A')->where($where)->field('id')->count();
        $Page = new Page($count, $this->page_size);

        $this->assign([
            'result' => $result,
            'page' => $Page->show(),
        ]);
        $this->display();
    }

    public function add() {
        $Categroy = M('GoodsCategory');
        if (IS_POST) {
            $data = [];
            $data['category_id'] = I('category_id', 0, 'intval');
            $data['goods_name'] = I('goods_name', '', 'addslashes,trim');
            $data['goods_sn'] = I('goods_sn', '', 'addslashes,trim');
            $data['goods_number'] = I('goods_number', 0, 'intval');
            $data['postage'] = I('postage', 0, 'floatval');
            $data['pay_balance'] = I('pay_balance', 0, 'floatval');
            $data['pay_integral'] = I('pay_integral', 0, 'floatval');
            $data['pay_coupon'] = I('pay_coupon', 0, 'floatval');
            $data['introduce'] = I('introduce', '', 'addslashes');
            $data['recommend'] = I('recommend', 0, 'tinyintval');
            $data['hot'] = I('hot', 0, 'tinyintval');
            $data['newest'] = I('newest', 0, 'tinyintval');
            $data['shelves'] = I('shelves', 0, 'tinyintval');
            $data['sort'] = I('sort', 1000, 'intval');
            $data['created_at'] = time();
            $catCount = $Categroy->where(['id' => $data['category_id']])->count();
            if ($catCount != 1) {
                return $this->error('id为' . $data['category_id'] . '的分类不存在');
            }

            if (!empty($_FILES['goods_thumb']) && $_FILES['goods_thumb']['error'] == 0) {
                $data['goods_thumb'] = $this->uploadImage($_FILES['goods_thumb']);
            }

            if (M('Goods')->data($data)->add() !== false) {
                return $this->success('商品添加成功');
            }

            return $this->error('商品添加失败' . M('Goods')->getError());

        } else {
            $cats = $Categroy->where(['status' => 1])->order('pid ASC,sort ASC,id DESC')->select();
            $this->assign(
                [
                    'category_list' => $this->treeCategory($cats, 0),
                ]
            );
            $this->display();
        }
    }

    public function edit() {
        $id = I('id', 0, 'intval');
        if (empty($id)) {
            return $this->error('参数错误');
        }
        $Goods = M('Goods');
        $result = $Goods->where(['id' => $id])->find();
        if (empty($result)) {
            return $this->error('没有找到该商品');
        }
        $Categroy = M('GoodsCategory');
        if (IS_POST) {
            $data = [];
            $data['id'] = I('id', 0, 'intval');
            $data['category_id'] = I('category_id', 0, 'intval');
            $data['goods_name'] = I('goods_name', '', 'addslashes,trim');
            $data['goods_sn'] = I('goods_sn', '', 'addslashes,trim');
            $data['goods_number'] = I('goods_number', 0, 'intval');
            $data['postage'] = I('postage', 0, 'floatval');
            $data['pay_balance'] = I('pay_balance', 0, 'floatval');
            $data['pay_integral'] = I('pay_integral', 0, 'floatval');
            $data['pay_coupon'] = I('pay_coupon', 0, 'floatval');
            $data['introduce'] = I('introduce', '', 'addslashes');
            $data['recommend'] = I('recommend', 0, 'tinyintval');
            $data['hot'] = I('hot', 0, 'tinyintval');
            $data['newest'] = I('newest', 0, 'tinyintval');
            $data['shelves'] = I('shelves', 0, 'tinyintval');
            $data['sort'] = I('sort', 1000, 'intval');
            $catCount = $Categroy->where(['id' => $data['category_id']])->count();
            if ($catCount != 1) {
                return $this->error('id为' . $data['category_id'] . '的分类不存在');
            }

            if (!empty($_FILES['goods_thumb']) && $_FILES['goods_thumb']['error'] == 0) {
                $data['goods_thumb'] = $this->uploadImage($_FILES['goods_thumb']);
            } else {
                unset($data['goods_thumb']);
            }

            if (M('Goods')->data($data)->save() !== false) {
                if (isset($data['goods_thumb'])) {
                    $this->unlinkImage(getcwd() . $result['goods_thumb']); //删除原来的缩略图
                }
                return $this->success('商品编辑成功');
            }

            return $this->error('商品编辑失败' . M('Goods')->getError());
        } else {
            $cats = $Categroy->where(['status' => 1])->order('pid ASC,sort ASC,id DESC')->select();
            $this->assign([
                'category_list' => $this->treeCategory($cats, $result['category_id']),
                'result' => $result
            ]);
            $this->display();
        }
    }

    public function recommend() {
        $id = I('id', 0, 'intval');
        $type = I('_type', 0, 'intval');
        if (empty($id)) {
            return $this->error('参数错误');
        }
        $goods = M('Goods')->where(['id' => $id])->find();
        if (empty($goods)) {
            return $this->error('商品不存在');
        }

        if ($goods['recommend'] == $type) {
            return $this->error('状态没有任何改变，无需更新');
        }

        M('Goods')->where(['id' => $goods['id']])->save([
            'recommend' => $type,
        ]);
        return $this->success('状态更新成功');
    }

    public function hot() {
        $id = I('id', 0, 'intval');
        $type = I('_type', 0, 'intval');
        if (empty($id)) {
            return $this->error('参数错误');
        }
        $goods = M('Goods')->where(['id' => $id])->find();
        if (empty($goods)) {
            return $this->error('商品不存在');
        }

        if ($goods['hot'] == $type) {
            return $this->error('状态没有任何改变，无需更新');
        }

        M('Goods')->where(['id' => $goods['id']])->save([
            'hot' => $type,
        ]);
        return $this->success('状态更新成功');
    }

    public function newest() {
        $id = I('id', 0, 'intval');
        $type = I('_type', 0, 'intval');
        if (empty($id)) {
            return $this->error('参数错误');
        }
        $goods = M('Goods')->where(['id' => $id])->find();
        if (empty($goods)) {
            return $this->error('商品不存在');
        }

        if ($goods['newest'] == $type) {
            return $this->error('状态没有任何改变，无需更新');
        }

        M('Goods')->where(['id' => $goods['id']])->save([
            'newest' => $type,
        ]);
        return $this->success('状态更新成功');
    }

    public function delete() {
        $id = I('id', 0, 'intval');
        if (empty($id)) {
            return $this->error('参数错误');
        }
        M('Goods')->delete($id);
        return $this->success('商品删除成功');
    }

    public function category() {
        $where = [];
        $Categroy = M('GoodsCategory');
        $result = $Categroy->where($where)->order('pid ASC,sort ASC,id DESC')->select();
        foreach ($result as $key => $val) {
            $result[$key]['add'] = '<a href="' . U('goods/category_add', ['pid' => $val['id']]) . '" class=" tooltip-info ajax-load" data-toggle="tooltip" data-placement="right" data-original-title="添加子分类"><i class="fa fa-plus"></i></a>';
            $result[$key]['delete_link'] = U('goods/category_delete', ['id' => $val['id']]);
            $result[$key]['edit_link'] = U('goods/category_edit', ['id' => $val['id']]);
            $result[$key]['statusString'] = $val['status'] == 1 ? '可用' : '禁用';
            $result[$key]['theme'] = $val['is_theme'] == 1 ? '是' : '否';
        }
        $Tree = new Tree($result);
        $Tree->icon = array("&nbsp;&nbsp;&nbsp;&nbsp; ", "&nbsp;&nbsp;&nbsp;├─ ", "&nbsp;&nbsp;&nbsp;└─ ");
        $Tree->nbsp = "&nbsp;&nbsp;&nbsp;";
        $html = "<tr>                    
                    <td width='80' class='input-group-xs'><input type='text' name='sort[\$id]' style='text-align:center' value='\$sort' class='form-control' /></td>
                    <td width='80' class='text-align-center'>\$id</td>
                    <td class='left'><span class='spacer'>\$spacer</span> \$name \$add</td>
                    <td width='120' class='text-align-center'>\$theme</td>
                    <td width='120' class='text-align-center'>\$statusString</td>
                    <td class='text-align-center'><a href='\$edit_link' class='ajax-load' ><i class='fa fa-edit'></i> 编辑</a> <a href='\$delete_link'  class='margin-left-10 ajax-link' data-confirm='确定删除该分类？'><i class='fa fa-trash-o'></i> 删除</a></td>
            </tr>";

        $result = $Tree->get_tree(0, $html);

        $this->assign([
            'result' => $result,
        ]);
        $this->display();
    }

    public function category_add() {
        $pid = I('pid', 0, 'intval');
        $cats = M('GoodsCategory')->order('sort ASC,id DESC')->select();
        if (IS_POST) {
            $data = [];
            $data['name'] = I('name', '', 'addslashes,trim');
            $data['pid'] = I('pid', 0, 'intval');
            $data['introduce'] = I('introduce', '', 'addslashes,trim');
            $data['sort'] = I('sort', 255, 'intval');
            $data['status'] = I('status', 1, 'intval');
            $data['is_theme'] = I('is_theme', 1, 'tinyintval');
            if (!empty($_FILES['icon']) && $_FILES['icon']['error'] == 0) {
                $data['icon'] = $this->uploadImage($_FILES['icon']);
            }

            if (M('GoodsCategory')->data($data)->add() !== false) {
                $this->cache_categories();
                return $this->success('分类添加成功');
            }

            $this->error('添加失败');
        } else {
            $this->assign('category_list', $this->treeCategory($cats, $pid));
            $this->display();
        }
    }

    public function category_edit() {

        if (IS_POST) {
            $data = [];
            $data['id'] = I('id', 0, 'intval');
            if (empty($data['id'])) {
                return $this->error('参数错误');
            }
            $data['name'] = I('name', '', 'addslashes,trim');
            $data['pid'] = I('pid', 0, 'intval');
            $data['introduce'] = I('introduce', '', 'addslashes,trim');
            $data['sort'] = I('sort', 255, 'intval');
            $data['status'] = I('status', 1, 'tinyintval');
            $data['is_theme'] = I('is_theme', 1, 'tinyintval');
            if (!empty($_FILES['icon']) && $_FILES['icon']['error'] == 0) {
                $data['icon'] = $this->uploadImage($_FILES['icon']);
            }

            if (M('GoodsCategory')->data($data)->save() !== false) {
                $this->cache_categories();
                return $this->success('分类编辑成功');
            }

            $this->error('编辑失败');
        } else {

            $id = I('id', 0, 'intval');
            $cats = M('GoodsCategory')->order('sort ASC,id DESC')->select();
            $result = [];
            foreach ($cats as $key => $cat) {
                if ($cat['id'] == $id) {
                    $result = $cat;
                    unset($cats[$key]);
                    break;
                }
            }
            $this->assign('category_list', $this->treeCategory($cats, $result['pid']));
            $this->assign($result);
            $this->display();
        }
    }

    public function category_cache() {
        $this->cache_categories();
        $this->success('缓存更新成功');
    }

    protected function cache_categories($return = false) {
        $cache = [];
        $category = M('GoodsCategory')->order('sort ASC,id DESC')->select();
        foreach ($category as $item) {
            $cache[$item['id']] = $item;
        }
        S($this->_category_cache, $cache);

        if ($return === true) {
            return $cache;
        }
    }

    /**
     * 分类排序
     */
    public function category_sort() {
        $sorts = I('sort', 0, 'intval');
        foreach ($sorts as $key => $val) {
            M('GoodsCategory')->where(['id' => $key])->setField('sort', $val);
        }
        $this->cache_categories();
        $this->success('操作成功');
    }

    public function category_delete() {
        $id = I('id', 0, 'intval');
        if (empty($id)) {
            return $this->error('参数错误');
        }
        $cat = M('GoodsCategory')->where(['id' => $id])->find();
        if (empty($cat)) {
            return $this->error('该分类不存在');
        }
        $childs = M('GoodsCategory')->where(['pid' => $id])->count();
        if ($childs > 0) {
            return $this->error('该分类有下级分类');
        }

        $goods = M('Goods')->where(['category_id' => $id])->count();
        if ($goods > 0) {
            return $this->error('该分类下有商品');
        }

        if (M('GoodsCategory')->delete($id) !== false) {
            $file = getcwd() . $cat['icon'];
            $this->unlinkImage($file);
            $this->cache_categories();
            return $this->success('删除成功');
        }
        return $this->success('删除失败');
    }

    protected function unlinkImage($path) {
        if (empty($path)) {
            return false;
        }
        if (!file_exists($path)) {
            return false;
        }

        if (unlink($path)) {
            return true;
        }

        return false;
    }

    public function comment() {
        $goods_id = I('goods_id', 0, 'intval');
        $user_id = I('user_id', 0, 'intval');
        $order_id = I('order_id', '', 'addslashes,trim');

        $where = [];
        if (!empty($goods_id)) {
            $where['A.goods_id'] = $goods_id;
        }
        if (!empty($user_id)) {
            $where['A.user_id'] = $user_id;
        }
        if (!empty($order_id)) {
            $where['D.order_id'] = $order_id;
        }
        $Model = M('GoodsComment');
        $count = $Model->alias('A')->where($where)->count();
        $Page = new Page($count, $this->page_size);
        $result = $Model->alias('A')->field('A.*, B.goods_name,B.goods_thumb,C.mobile,D.order_id as orderid')
            ->join(C('DB_PREFIX') . 'goods as B on A.goods_id = B.id', 'left')
            ->join(C('DB_PREFIX') . 'user as C ON C.id = A.user_id', 'left')
            ->join(C('DB_PREFIX') . 'goods_order as D ON D.id = A.order_id', 'left')
            ->where($where)->order('id DESC')->page($Page->nowPage, $this->page_size)->select();

        $this->assign([
            'result' => $result,
            'page' => $Page->show(),
        ]);

        $this->display();
    }

    public function comment_delete() {
        $id = I('id', 0, 'intval');
        if (empty($id)) {
            return $this->error('参数错误');
        }
        $comment = M('GoodsComment')->where(['id' => $id])->delete();
        if ($comment !== false) {
            return $this->success('删除成功');
        }

        return $this->error('删除失败');
    }
}